/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Evolucion.java
 *
 * Created on 09-11-2012, 10:48:14 AM
 */
package SubsistemaPaciente.Fichas;

import clienteSandraParada.Login;
import java.awt.Color;
import java.util.Calendar;
import java.util.Date;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import service.HeuristicMixedException_Exception;
import service.HeuristicRollbackException_Exception;
import service.SystemException_Exception;

/**
 *
 * @author Jacqueline
 */
public class EvolucionSiqui extends javax.swing.JDialog {

    public static Long ficha;
    FichaSiquiatra fichaSiqui;
    public static Long idFichaEvo;
    public static Long idEvolucion;
    String fichaActual;
    String valorAnterior;
    String valorNuevo;

    /** Creates new form Evolucion */
    public EvolucionSiqui(java.awt.Frame parent, boolean modal, FichaSiquiatra p) {
        super(parent, modal);
        initComponents();
        valorAnterior = "";
        valorNuevo = "";
        setIconImage(new ImageIcon(getClass().getResource("/GUI/Img/logo2.png")).getImage());
        this.fichaSiqui = p;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        accionEvolucion = new javax.swing.JButton();
        cancelarEvolucion = new javax.swing.JButton();
        evolucionClinica = new javax.swing.JPanel();
        jLabel13 = new javax.swing.JLabel();
        jLabel15 = new javax.swing.JLabel();
        sesion = new javax.swing.JTextField();
        fechaEvolucion = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        comentarioEvolucion = new javax.swing.JTextArea();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        mensajeria = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        accionEvolucion.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos16X16/Aceptar.png"))); // NOI18N
        accionEvolucion.setText("Agregar");
        accionEvolucion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                accionEvolucionActionPerformed1(evt);
            }
        });

        cancelarEvolucion.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos16X16/Cancelar.png"))); // NOI18N
        cancelarEvolucion.setText("Cancelar");
        cancelarEvolucion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelarEvolucionActionPerformed(evt);
            }
        });

        evolucionClinica.setBorder(javax.swing.BorderFactory.createTitledBorder("Evolución clínica"));

        jLabel13.setText("Fecha:");

        jLabel15.setText("Sesión:");

        javax.swing.GroupLayout evolucionClinicaLayout = new javax.swing.GroupLayout(evolucionClinica);
        evolucionClinica.setLayout(evolucionClinicaLayout);
        evolucionClinicaLayout.setHorizontalGroup(
            evolucionClinicaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(evolucionClinicaLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel13)
                .addGap(37, 37, 37)
                .addComponent(fechaEvolucion, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(83, 83, 83)
                .addComponent(jLabel15)
                .addGap(18, 18, 18)
                .addComponent(sesion, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(26, Short.MAX_VALUE))
        );
        evolucionClinicaLayout.setVerticalGroup(
            evolucionClinicaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(evolucionClinicaLayout.createSequentialGroup()
                .addGroup(evolucionClinicaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(evolucionClinicaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel15)
                        .addComponent(sesion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(evolucionClinicaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel13)
                        .addComponent(fechaEvolucion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jLabel1.setText("Comentario:");

        comentarioEvolucion.setColumns(20);
        comentarioEvolucion.setRows(5);
        jScrollPane1.setViewportView(comentarioEvolucion);

        jLabel2.setText("*");

        jLabel3.setText("* Dato obligatorio");

        mensajeria.setText("Área de mensajería");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(evolucionClinica, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(10, 10, 10)
                                        .addComponent(jLabel1)
                                        .addGap(18, 18, 18)
                                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 283, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                        .addComponent(jLabel3)
                                        .addGap(285, 285, 285)))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel2)
                                .addGap(0, 0, Short.MAX_VALUE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGap(0, 188, Short.MAX_VALUE)
                                .addComponent(accionEvolucion)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(cancelarEvolucion)))
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(mensajeria, javax.swing.GroupLayout.PREFERRED_SIZE, 197, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(59, 59, 59))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(evolucionClinica, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 14, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(accionEvolucion)
                            .addComponent(cancelarEvolucion))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(mensajeria)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 82, Short.MAX_VALUE)
                        .addComponent(jLabel3)
                        .addGap(61, 61, 61))))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void accionEvolucionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_accionEvolucionActionPerformed
        //Dialogo de evolucion de una ficha
        fichaSiqui.mensajeriaFormulario.setText("");
        boolean datosObligatorios = llenoDatosObligatorios();
        if (this.getTitle().equals("Agregar Evolucion") && datosObligatorios == true) {
            Long idEvolucion = agregarEvolucionBD(ficha, Integer.parseInt(this.sesion.getText()), this.fechaEvolucion.getText(),
                    this.comentarioEvolucion.getText(), true);
            fichaSiqui.agregarDatoTablaEvolucion(Integer.parseInt(this.sesion.getText()), this.fechaEvolucion.getText(),
                    this.comentarioEvolucion.getText());
            fichaSiqui.mensajeriaFormulario.setText("La evolución se ha sido agregado exitosamente");
            this.dispose();
        } else if (datosObligatorios == false) {
            this.mensajeria.setText("Complete el campo obligatorio");
            this.mensajeria.setForeground(Color.red);
        } else if (this.getTitle().equals("Modificar Evolucion")) {
            int s = Integer.parseInt(this.sesion.getText());
            modificarEvolucionBD(idEvolucion, idFichaEvo, s, this.fechaEvolucion.getText(),
                    this.comentarioEvolucion.getText(), true);
            fichaSiqui.modificarDatoTabla(s, this.fechaEvolucion.getText(), this.comentarioEvolucion.getText());
            fichaSiqui.mensajeriaFormulario.setText("La evolución ha sido modificada exitosamente");
            this.dispose();
        } else if (this.getTitle().equals("Ver Evolucion")) {
            this.dispose();
            fichaSiqui.mensajeriaFormulario.setText("");
        }
}//GEN-LAST:event_accionEvolucionActionPerformed

    private void cancelarEvolucionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelarEvolucionActionPerformed
        // cancela agregar evaluacion de ficha
        this.dispose();
}//GEN-LAST:event_cancelarEvolucionActionPerformed

    private void accionEvolucionActionPerformed1(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_accionEvolucionActionPerformed1
        // TODO add your handling code here:
        fichaSiqui.mensajeriaFormulario.setText("");
        boolean datosObligatorios = llenoDatosObligatorios();
        if(this.getTitle().equals("Agregar Evolucion")&& datosObligatorios==true){
            Long idEvolucion= agregarEvolucionBD(ficha,Integer.parseInt(this.sesion.getText()),this.fechaEvolucion.getText(),
                                                this.comentarioEvolucion.getText(),true);
            fichaSiqui.agregarDatoTablaEvolucion(Integer.parseInt(this.sesion.getText()),this.fechaEvolucion.getText(),
                    this.comentarioEvolucion.getText());
            fichaSiqui.mensajeriaFormulario.setText("La evolución se ha sido agregado exitosamente");
            this.dispose();
        }
        else if(datosObligatorios == false){
            this.mensajeria.setText("Complete el campo obligatorio");
            this.mensajeria.setForeground(Color.red);
        }
        else if(this.getTitle().equals("Modificar Evolucion")){
            int s=Integer.parseInt(this.sesion.getText());
            modificarEvolucionBD(idEvolucion,idFichaEvo,s,this.fechaEvolucion.getText(),
                    this.comentarioEvolucion.getText(),true);
            fichaSiqui.modificarDatoTabla(s,this.fechaEvolucion.getText(),this.comentarioEvolucion.getText());
            fichaSiqui.mensajeriaFormulario.setText("La evolución ha sido modificada exitosamente");
            this.dispose();
        }
        else if(this.getTitle().equals("Ver Evolucion")){
            this.dispose();
            fichaSiqui.mensajeriaFormulario.setText("");
        }
    }//GEN-LAST:event_accionEvolucionActionPerformed1
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton accionEvolucion;
    private javax.swing.JButton cancelarEvolucion;
    private javax.swing.JTextArea comentarioEvolucion;
    private javax.swing.JPanel evolucionClinica;
    private javax.swing.JTextField fechaEvolucion;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel mensajeria;
    private javax.swing.JTextField sesion;
    // End of variables declaration//GEN-END:variables

    public void configurarBotones(String formulario) {
        if (formulario.equals("agregar")) {
            this.accionEvolucion.setText("Aceptar");
            this.accionEvolucion.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos16X16/Agregar.png")));
        } else if (formulario.equals("modificar")) {
            this.accionEvolucion.setText("Guardar");
            this.accionEvolucion.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos16X16/Agregar.png")));
        } else {
            this.accionEvolucion.setText("Aceptar");
            this.accionEvolucion.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos16X16/Aceptar.png")));
        }

    }

    public void limpiarFormularioEvolucion() {
        this.sesion.setText("");
        this.fechaEvolucion.setText("");
        this.comentarioEvolucion.setText("");
    }

    void agregarDatos(String sesion) {
        this.sesion.setText(sesion);
        this.sesion.setEditable(false);
        this.fechaEvolucion.setText(fechaActual());
        this.fechaEvolucion.setEditable(false);
    }

    public String fechaActual() {
        Calendar cal1 = Calendar.getInstance();
        int mes = cal1.get(Calendar.MONTH) + 1;
        return ("" + cal1.get(Calendar.DATE) + "-" + mes + "-" + cal1.get(Calendar.YEAR));
    }

    public void llenarDatosFormularioEvolucion(service.Evolucion evolucion) {
        this.fechaEvolucion.setText(evolucion.getFecha());
        this.sesion.setText(Integer.toString(evolucion.getSesion()));
        this.comentarioEvolucion.setText(evolucion.getComentario());
        this.fechaEvolucion.setEditable(false);
        this.sesion.setEditable(false);
    }

    private Long agregarEvolucionBD(Long fichaClinica, int sesion, String fecha, String comentario, boolean activo) {
        // Llamar al Web Service
        service.EvolucionWSService service = new service.EvolucionWSService();
        service.EvolucionWS port = service.getEvolucionWSPort();
        // TODO process result here
        service.FichaSiquiatra f = buscarFichaSiquiatra(fichaClinica);
        valorNuevo = "Sesión: " + sesion + "\n" + "Fecha: " + fecha + "\n" + "Comentario: " + comentario;
        registrar(Login.getUser(), "Ficha siquiatría", "Agregó evolución sesión: " + sesion + " a profesional: " + f.getProfesional() + "de paciente: " + f.getPaciente(), "", valorNuevo);
        Long idEvo = port.agregarEvolucion(fichaClinica, sesion, fecha, comentario, activo);
        return idEvo;
    }

    private void modificarEvolucionBD(Long idEvolucion, Long idFichaEvo, int sesion, String fecha, String comentario, boolean activo) {
        try {
            service.EvolucionWSService service = new service.EvolucionWSService();
            service.EvolucionWS port = service.getEvolucionWSPort();
            service.Evolucion evo = (service.Evolucion) cargarEvolucion(idEvolucion);
            valorAnterior = "Sesión: " + evo.getSesion() + "\n" + "Fecha: " + evo.getFecha() + "\n" + "Comentario: " + evo.getComentario();
            valorNuevo = "Sesión: " + sesion + "\n" + "Fecha: " + fecha + "\n" + "Comentario: " + comentario;
            service.FichaSiquiatra f = buscarFichaSiquiatra(idFichaEvo);
            registrar(Login.getUser(), "Ficha siquiatría", "Modificó evolución sesión: " + sesion+ " a profesional: " + f.getProfesional() + "de paciente: " + f.getPaciente(), "", valorNuevo);
            boolean resultado = port.modificarEvolucion(idEvolucion, idFichaEvo, sesion, fecha, comentario, activo);
        } catch (Exception ex) {
            // TODO handle custom exceptions here
        }
    }

    private boolean llenoDatosObligatorios() {
        if (this.comentarioEvolucion.getText().equals("")) {
            return false;
        }
        return true;
    }

    void habilitarCamposFormulario(boolean b) {
        this.comentarioEvolucion.setEditable(b);
    }

    void ocultarCamposObligatorios(boolean b) {
        if (b == false) {
            this.jLabel3.setText("*Dato obligatorio");
            this.mensajeria.setText("Área Mensajería");
            this.jLabel2.setText("*");
        } else {
            this.jLabel3.setText("");
            this.mensajeria.setText("");
            this.jLabel2.setText("");
        }
    }

    private static Long registrar(service.Usuario usuario, java.lang.String modulo, java.lang.String accion, java.lang.String valorAnterior, java.lang.String valorNuevo) {
        service.BitacoraWSService service = new service.BitacoraWSService();
        service.BitacoraWS port = service.getBitacoraWSPort();
        return port.registrar(usuario, modulo, accion, valorAnterior, valorNuevo);
    }

    private static Object cargarEvolucion(java.lang.Long id) throws HeuristicRollbackException_Exception, HeuristicMixedException_Exception, SystemException_Exception {
        service.EvolucionWSService service = new service.EvolucionWSService();
        service.EvolucionWS port = service.getEvolucionWSPort();
        return port.cargarEvolucion(id);
    }
        public service.FichaSiquiatra buscarFichaSiquiatra(Long fichaSico) {
        service.FichaSiquiatraWSService service = new service.FichaSiquiatraWSService();
        service.FichaSiquiatraWS port = service.getFichaSiquiatraWSPort();

        java.util.List<service.FichaSiquiatra> fichasSiquiatra = port.listarFichasSiquiatra();
        //buscar paciente por el rut
        for (int i = 0; i < fichasSiquiatra.size(); i++) {
            if (fichasSiquiatra.get(i).getId().equals(fichaSico)) {
                return fichasSiquiatra.get(i);
            }
        }
        return null;
    }
}
